package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.atguigu.lease.common.constant.RedisConstant.ADMIN_LOGIN_PREFIX;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SystemUserMapper systemUserMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha captcha = new SpecCaptcha(130,48,4);
        //生成验证码字母（全大写）
        String code = captcha.text().toLowerCase();
        //通过UUID方法生成key，用于标识用户身份，此时用户尚未登录
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        //将key和code存储到redis上，并设置过期时间60s
        redisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        //将image和key返回给前端用于显示验证码图形和让用户带key，用户名，用户Id，和自己输入的验证码用于身份验证
        return new CaptchaVo(captcha.toBase64(),key);
    }

    @Override
    public String login(LoginVo loginVo) {
        String captchaCode = loginVo.getCaptchaCode();
        //是否
        if(!StringUtils.hasLength(captchaCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //loginVo.getCaptchaKey()用户传来的UUID
        if(!redisTemplate.hasKey(loginVo.getCaptchaKey())){
            //redis中存储的key和code已过期
           throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //redis中存储的正确的验证码 get入参为键，返回值为code值
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        //判断用户输入的验证码和redis中存储的是否一致
        if(!code.equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        //将密码加密后作为查询条件
        queryWrapper.eq(SystemUser::getPassword, DigestUtils.sha256Hex(loginVo.getPassword()));
        SystemUser systemUser = systemUserMapper.selectOne(queryWrapper);

        //如果数据库中没有数据，则无需封装成指定对象，直接返回null
        if(systemUser == null){
            //如果未查到用户信息，表明输入用户名或密码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断用户状态是否为禁用状态
        if(systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //根据用户ID生成token
        return JwtUtil.createToken(systemUser.getId());
    }
}
